//
//  UIBezierPath+GetAllPoints.m
//  YMDrawingBoard
//
//  Created by 刘家俊 on 2020/12/2.
//  Copyright © 2020 余默. All rights reserved.
//

#import "UIBezierPath+GetAllPoints.h"

#define VALUE(_INDEX_) [NSValue valueWithCGPoint:points[_INDEX_]]

@implementation UIBezierPath (GetAllPoints)

void getPointsFromBezier(void *info,const CGPathElement *element){
    NSMutableArray *bezierPoints = (__bridge NSMutableArray *)info;
    CGPathElementType type = element->type;
    CGPoint *points = element->points;
    
    if (type != kCGPathElementCloseSubpath) {
        [bezierPoints addObject:VALUE(0)];
        if ((type != kCGPathElementAddLineToPoint) && (type != kCGPathElementMoveToPoint)) {
            [bezierPoints addObject:VALUE(1)];
        }
    }
    
    if (type == kCGPathElementAddCurveToPoint) {
        [bezierPoints addObject:VALUE(2)];
    }
    
}

//获取曲线的点，CGPoint数组
- (NSArray *)linesPoints {
    NSMutableArray *points = [NSMutableArray array];
    CGPathApply(self.CGPath, (__bridge void *)points, getPointsFromBezier);
    return points;
}

//数组转换，将CGPoint数组转换成，（x,y）字典数组
- (NSArray *)points
{
    NSArray *points = [self linesPoints];
    NSMutableArray *newPoints = [NSMutableArray new];
    for (NSInteger i = 0; i < points.count; i++) {
        CGPoint point = [points[i] CGPointValue];  //将元素转换成CGPoint
        NSMutableDictionary *dict = [NSMutableDictionary new];
        double x = point.x;
        double y = point.y;
        
        dict[@"x"] = @(x);
        dict[@"y"] = @(y);
        
        [newPoints addObject:dict];
    }

    return newPoints;
}

@end
